package com.waves.core.handle;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.waves.core.constant.DataSourceConstant;
import com.waves.core.utils.LoginUtils;
import com.waves.core.web.domain.entities.User;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/**
 * mybatisPlus实现自动填充数据库表中的字段值
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        User user = LoginUtils.getUser();
        Long userId = user.getId();
        String userName = user.getName();

        this.strictInsertFill(metaObject, DataSourceConstant.CREATED_TIME,
                System::currentTimeMillis, Long.class);
        this.strictInsertFill(metaObject, DataSourceConstant.CREATED_BY,
                () -> userId, Long.class);
        this.strictInsertFill(metaObject, DataSourceConstant.CREATED_NAME,
                () -> userName, String.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        User user = LoginUtils.getUser();
        Long userId = user.getId();
        String userName = user.getName();

        this.strictUpdateFill(metaObject, DataSourceConstant.UPDATED_TIME,
                System::currentTimeMillis, Long.class);
        this.strictUpdateFill(metaObject, DataSourceConstant.UPDATED_BY,
                () -> userId, Long.class);
        this.strictUpdateFill(metaObject, DataSourceConstant.UPDATED_NAME,
                () -> userName, String.class);
    }
}
